package com.lsfb.signsys.view.simpletoolbar;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MarginLayoutParamsCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.widget.AppCompatImageButton;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.TintTypedArray;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.ViewUtils;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import com.lsfb.signsys.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zgscwjm on 2018/4/8.
 */

public class SimpleToolbar extends ViewGroup {

    private TextView mTitleTextView;

    private ImageButton mNavButtonView;


    private int mTitleMarginStart;
    private int mTitleMarginEnd;
    private int mTitleMarginTop;
    private int mTitleMarginBottom;

    /**
     * 这里是文字
     */
    private CharSequence mTitleText;

    /**
     * 按钮的位置
     */
    int mButtonGravity;


    View mExpandedActionView;


    private int mTitleTextColor;
    private final int[] mTempMargins = new int[2];


    private final ArrayList<View> mTempViews = new ArrayList<View>();


    private int mTitleTextAppearance;


    private int mContentInsetStartWithNavigation;

    // Used to hold views that will be removed while we have an expanded action view.
    private final ArrayList<View> mHiddenViews = new ArrayList<>();

    public SimpleToolbar(Context context) {
        this(context, null);
    }


    public SimpleToolbar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    private int mGravity = GravityCompat.START | Gravity.CENTER_VERTICAL;

    public SimpleToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

//        // Need to use getContext() here so that we use the themed context


        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SimpleToolbar, defStyleAttr, 0);


        mButtonGravity = a.getInteger(R.styleable.SimpleToolbar_buttonGravitys, Gravity.TOP);

        //设置margin
        int titleMargin = a.getDimensionPixelOffset(R.styleable.SimpleToolbar_titleMargins, 0);
        mTitleMarginStart = mTitleMarginEnd = mTitleMarginTop = mTitleMarginBottom = titleMargin;

        final int marginStart = a.getDimensionPixelOffset(R.styleable.SimpleToolbar_titleMarginStart, -1);
        if (marginStart >= 0) {
            mTitleMarginStart = marginStart;
        }

        final int marginEnd = a.getDimensionPixelOffset(R.styleable.SimpleToolbar_titleMarginEnd, -1);
        if (marginEnd >= 0) {
            mTitleMarginEnd = marginEnd;
        }


        final int marginTop = a.getDimensionPixelOffset(R.styleable.SimpleToolbar_titleMarginTop, -1);
        if (marginTop >= 0) {
            mTitleMarginTop = marginTop;
        }


        final int marginBottom = a.getDimensionPixelOffset(R.styleable.SimpleToolbar_titleMarginBottom, -1);
        if (marginBottom >= 0) {
            mTitleMarginBottom = marginBottom;
        }


//        mContentInsetStartWithNavigation = a.getDimensionPixelOffset(
//                android.support.v7.appcompat.R.styleable.Toolbar_contentInsetStartWithNavigation, RtlSpacingHelper.UNDEFINED);


        //设置文字
        final CharSequence title = a.getText(R.styleable.SimpleToolbar_title);
        if (!TextUtils.isEmpty(title)) {
            setTitle(title);
        }

        //设置文字颜色
        if (a.hasValue(R.styleable.SimpleToolbar_titleTextColor)) {
            setTitleTextColor(a.getColor(R.styleable.SimpleToolbar_titleTextColor, 0xffffffff));
        }


        //设置导航视图图标
        final Drawable navIcon = a.getDrawable(R.styleable.SimpleToolbar_navigationIcon);
        if (navIcon != null) {
            setNavigationIcon(navIcon);
        }

        //设置导航视图内容描述
        final CharSequence navDesc = a.getText(android.support.v7.appcompat.R.styleable.Toolbar_navigationContentDescription);
        if (!TextUtils.isEmpty(navDesc)) {
            setNavigationContentDescription(navDesc);
        }

        a.recycle();

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = 0;
        int height = 0;
        int childState = 0;

        final int[] collapsingMargins = mTempMargins;
        final int marginStartIndex;
        final int marginEndIndex;


//        if (ViewUtils.isLayoutRtl(this)) {
//            marginStartIndex = 1;
//            marginEndIndex = 0;
//        } else {


        marginStartIndex = 0;
        marginEndIndex = 1;
//        }

        // System views measure first.

        int navWidth = 0;

        if (shouldLayout(mNavButtonView)) {
            measureChildConstrained(mNavButtonView, widthMeasureSpec, width, heightMeasureSpec, 0, 3000);


            navWidth = mNavButtonView.getMeasuredWidth() + getHorizontalMargins(mNavButtonView);

            height = Math.max(height, mNavButtonView.getMeasuredHeight() + getVerticalMargins(mNavButtonView));

            childState = View.combineMeasuredStates(childState, mNavButtonView.getMeasuredState());
        }
//        if (shouldLayout(mNavButtonView)) {
//            measureChildConstrained(mNavButtonView, widthMeasureSpec, width, heightMeasureSpec, 0,
//                    mMaxButtonHeight);
//            navWidth = mNavButtonView.getMeasuredWidth() + getHorizontalMargins(mNavButtonView);
//            height = Math.max(height, mNavButtonView.getMeasuredHeight() +
//                    getVerticalMargins(mNavButtonView));
//            childState = View.combineMeasuredStates(childState,
//                    mNavButtonView.getMeasuredState());
//        }

//        if (shouldLayout(mCollapseButtonView)) {
//            measureChildConstrained(mCollapseButtonView, widthMeasureSpec, width,
//                    heightMeasureSpec, 0, mMaxButtonHeight);
//            navWidth = mCollapseButtonView.getMeasuredWidth() +
//                    getHorizontalMargins(mCollapseButtonView);
//            height = Math.max(height, mCollapseButtonView.getMeasuredHeight() +
//                    getVerticalMargins(mCollapseButtonView));
//            childState = View.combineMeasuredStates(childState,
//                    mCollapseButtonView.getMeasuredState());
//        }

        final int contentInsetStart = getCurrentContentInsetStart();
        width += Math.max(contentInsetStart, navWidth);
        collapsingMargins[marginStartIndex] = Math.max(0, contentInsetStart - navWidth);

        int menuWidth = 0;
//        if (shouldLayout(mMenuView)) {
//            measureChildConstrained(mMenuView, widthMeasureSpec, width, heightMeasureSpec, 0,
//                    mMaxButtonHeight);
//            menuWidth = mMenuView.getMeasuredWidth() + getHorizontalMargins(mMenuView);
//            height = Math.max(height, mMenuView.getMeasuredHeight() +
//                    getVerticalMargins(mMenuView));
//            childState = View.combineMeasuredStates(childState,
//                    mMenuView.getMeasuredState());
//        }

        final int contentInsetEnd = getCurrentContentInsetEnd();
        width += Math.max(contentInsetEnd, menuWidth);
        collapsingMargins[marginEndIndex] = Math.max(0, contentInsetEnd - menuWidth);

//        if (shouldLayout(mExpandedActionView)) {
//            width += measureChildCollapseMargins(mExpandedActionView, widthMeasureSpec, width,
//                    heightMeasureSpec, 0, collapsingMargins);
//            height = Math.max(height, mExpandedActionView.getMeasuredHeight() +
//                    getVerticalMargins(mExpandedActionView));
//            childState = View.combineMeasuredStates(childState,
//                    mExpandedActionView.getMeasuredState());
//        }

//        if (shouldLayout(mLogoView)) {
//            width += measureChildCollapseMargins(mLogoView, widthMeasureSpec, width,
//                    heightMeasureSpec, 0, collapsingMargins);
//            height = Math.max(height, mLogoView.getMeasuredHeight() +
//                    getVerticalMargins(mLogoView));
//            childState = View.combineMeasuredStates(childState,
//                    mLogoView.getMeasuredState());
//        }

        final int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = getChildAt(i);
            final SimpleToolbar.LayoutParams lp = (SimpleToolbar.LayoutParams) child.getLayoutParams();
            if (lp.mViewType != SimpleToolbar.LayoutParams.CUSTOM || !shouldLayout(child)) {
                // We already got all system views above. Skip them and GONE views.
                continue;
            }

            width += measureChildCollapseMargins(child, widthMeasureSpec, width,
                    heightMeasureSpec, 0, collapsingMargins);
            height = Math.max(height, child.getMeasuredHeight() + getVerticalMargins(child));
            childState = View.combineMeasuredStates(childState, child.getMeasuredState());
        }

        int titleWidth = 0;
        int titleHeight = 0;
        final int titleVertMargins = mTitleMarginTop + mTitleMarginBottom;
        final int titleHorizMargins = mTitleMarginStart + mTitleMarginEnd;



        if (shouldLayout(mTitleTextView)) {
            titleWidth = measureChildCollapseMargins(mTitleTextView, widthMeasureSpec,
                    width + titleHorizMargins, heightMeasureSpec, titleVertMargins,
                    collapsingMargins);
            titleWidth = mTitleTextView.getMeasuredWidth() + getHorizontalMargins(mTitleTextView);
            titleHeight = mTitleTextView.getMeasuredHeight() + getVerticalMargins(mTitleTextView);
            childState = View.combineMeasuredStates(childState, mTitleTextView.getMeasuredState());
        }
//        if (shouldLayout(mSubtitleTextView)) {
//            titleWidth = Math.max(titleWidth, measureChildCollapseMargins(mSubtitleTextView,
//                    widthMeasureSpec, width + titleHorizMargins,
//                    heightMeasureSpec, titleHeight + titleVertMargins,
//                    collapsingMargins));
//            titleHeight += mSubtitleTextView.getMeasuredHeight() +
//                    getVerticalMargins(mSubtitleTextView);
//            childState = View.combineMeasuredStates(childState,
//                    mSubtitleTextView.getMeasuredState());
//        }

        width += titleWidth;
        height = Math.max(height, titleHeight);

        // Measurement already took padding into account for available space for the children,
        // add it in for the final size.
        width += getPaddingLeft() + getPaddingRight();
        height += getPaddingTop() + getPaddingBottom();

        final int measuredWidth = View.resolveSizeAndState(
                Math.max(width, getSuggestedMinimumWidth()),
                widthMeasureSpec, childState & View.MEASURED_STATE_MASK);
        final int measuredHeight = View.resolveSizeAndState(
                Math.max(height, getSuggestedMinimumHeight()),
                heightMeasureSpec, childState << View.MEASURED_HEIGHT_STATE_SHIFT);

        setMeasuredDimension(measuredWidth, shouldCollapse() ? 0 : measuredHeight);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int width = getWidth();
        final int height = getHeight();
        final int paddingLeft = getPaddingLeft();
        final int paddingRight = getPaddingRight();
        final int paddingTop = getPaddingTop();
        final int paddingBottom = getPaddingBottom();
        int left = paddingLeft;
        int right = width - paddingRight;

        final int[] collapsingMargins = mTempMargins;
        collapsingMargins[0] = collapsingMargins[1] = 0;

        // Align views within the minimum toolbar height, if set.
        final int minHeight = ViewCompat.getMinimumHeight(this);
        final int alignmentHeight = minHeight >= 0 ? Math.min(minHeight, b - t) : 0;

        if (shouldLayout(mNavButtonView)) {
            left = layoutChildLeft(mNavButtonView, left, collapsingMargins,
                    alignmentHeight);
        }

//        if (shouldLayout(mCollapseButtonView)) {
//            if (isRtl) {
//                right = layoutChildRight(mCollapseButtonView, right, collapsingMargins,
//                        alignmentHeight);
//            } else {
//                left = layoutChildLeft(mCollapseButtonView, left, collapsingMargins,
//                        alignmentHeight);
//            }
//        }

//        if (shouldLayout(mMenuView)) {
//            if (isRtl) {
//                left = layoutChildLeft(mMenuView, left, collapsingMargins,
//                        alignmentHeight);
//            } else {
//                right = layoutChildRight(mMenuView, right, collapsingMargins,
//                        alignmentHeight);
//            }
//        }

        final int contentInsetLeft = getCurrentContentInsetLeft();
//        final int contentInsetRight = getCurrentContentInsetRight();
//        collapsingMargins[0] = Math.max(0, contentInsetLeft - left);
//        collapsingMargins[1] = Math.max(0, contentInsetRight - (width - paddingRight - right));
        left = Math.max(left, contentInsetLeft);
//        right = Math.min(right, width - paddingRight - contentInsetRight);

//        if (shouldLayout(mExpandedActionView)) {
//            if (isRtl) {
//                right = layoutChildRight(mExpandedActionView, right, collapsingMargins,
//                        alignmentHeight);
//            } else {
//                left = layoutChildLeft(mExpandedActionView, left, collapsingMargins,
//                        alignmentHeight);
//            }
//        }

//        if (shouldLayout(mLogoView)) {
//            if (isRtl) {
//                right = layoutChildRight(mLogoView, right, collapsingMargins,
//                        alignmentHeight);
//            } else {
//                left = layoutChildLeft(mLogoView, left, collapsingMargins,
//                        alignmentHeight);
//            }
//        }

        final boolean layoutTitle = shouldLayout(mTitleTextView);
        int titleHeight = 0;
        if (layoutTitle) {

            //计算出 标题的高度
            final SimpleToolbar.LayoutParams lp = (SimpleToolbar.LayoutParams) mTitleTextView.getLayoutParams();
            titleHeight += lp.topMargin + mTitleTextView.getMeasuredHeight() + lp.bottomMargin;
        }

        if (layoutTitle) {


            int titleTop = 0;
            final View topChild = mTitleTextView;
//            final View bottomChild = mTitleTextView;
            final SimpleToolbar.LayoutParams toplp = (SimpleToolbar.LayoutParams) topChild.getLayoutParams();
//            final SimpleToolbar.LayoutParams bottomlp = (SimpleToolbar.LayoutParams) bottomChild.getLayoutParams();


            final boolean titleHasWidth = (layoutTitle && (mTitleTextView.getMeasuredWidth() > 0));


            switch (mGravity & Gravity.VERTICAL_GRAVITY_MASK) {
                case Gravity.TOP:
                    titleTop = getPaddingTop() + toplp.topMargin + mTitleMarginTop;
                    break;
                default:
                case Gravity.CENTER_VERTICAL:
                    final int space = height - paddingTop - paddingBottom;
                    int spaceAbove = (space - titleHeight) / 2;
                    if (spaceAbove < toplp.topMargin + mTitleMarginTop) {
                        spaceAbove = toplp.topMargin + mTitleMarginTop;
                    } else {
                        final int spaceBelow = height - paddingBottom - titleHeight -
                                spaceAbove - paddingTop;
//                        if (spaceBelow < toplp.bottomMargin + mTitleMarginBottom) {
//                            spaceAbove = Math.max(0, spaceAbove -
//                                    (bottomlp.bottomMargin + mTitleMarginBottom - spaceBelow));
//                        }
                    }
                    titleTop = paddingTop + spaceAbove;
                    break;

                case Gravity.CENTER_HORIZONTAL:

                    break;
//                case Gravity.BOTTOM:
//                    titleTop = height - paddingBottom - bottomlp.bottomMargin - mTitleMarginBottom -
//                            titleHeight;
//                    break;
            }

            final int ld = (titleHasWidth ? mTitleMarginStart : 0) - collapsingMargins[0];
            left += Math.max(0, ld);
            collapsingMargins[0] = Math.max(0, -ld);


            int titleLeft = left;

            int CurrentWitdhPoint=getMeasuredWidth()/2;

            if (layoutTitle) {
                final SimpleToolbar.LayoutParams lp = (SimpleToolbar.LayoutParams) mTitleTextView.getLayoutParams();

                titleLeft = CurrentWitdhPoint - mTitleTextView.getMeasuredWidth()/2;

                final int titleRight = titleLeft + mTitleTextView.getMeasuredWidth();
                final int titleBottom = titleTop + mTitleTextView.getMeasuredHeight();
                mTitleTextView.layout(titleLeft, titleTop, titleRight, titleBottom);
                titleLeft = titleRight + mTitleMarginEnd;
                titleTop = titleBottom + lp.bottomMargin;
            }

            left = titleLeft;

        }
//        }

        // Get all remaining children sorted for layout. This is all prepared
        // such that absolute layout direction can be used below.

        addCustomViewsWithGravity(mTempViews, Gravity.LEFT);
        final int leftViewsCount = mTempViews.size();
        for (int i = 0; i < leftViewsCount; i++) {
            left = layoutChildLeft(mTempViews.get(i), left, collapsingMargins,
                    alignmentHeight);
        }

        addCustomViewsWithGravity(mTempViews, Gravity.RIGHT);
        final int rightViewsCount = mTempViews.size();
        for (int i = 0; i < rightViewsCount; i++) {
            right = layoutChildRight(mTempViews.get(i), right, collapsingMargins,
                    alignmentHeight);
        }

        // Centered views try to center with respect to the whole bar, but views pinned
        // to the left or right can push the mass of centered views to one side or the other.
        addCustomViewsWithGravity(mTempViews, Gravity.CENTER_HORIZONTAL);
        final int centerViewsWidth = getViewListMeasuredWidth(mTempViews, collapsingMargins);
        final int parentCenter = paddingLeft + (width - paddingLeft - paddingRight) / 2;
        final int halfCenterViewsWidth = centerViewsWidth / 2;
        int centerLeft = parentCenter - halfCenterViewsWidth;
        final int centerRight = centerLeft + centerViewsWidth;
        if (centerLeft < left) {
            centerLeft = left;
        } else if (centerRight > right) {
            centerLeft -= centerRight - right;
        }

        final int centerViewsCount = mTempViews.size();
        for (int i = 0; i < centerViewsCount; i++) {
            centerLeft = layoutChildLeft(mTempViews.get(i), centerLeft, collapsingMargins,
                    alignmentHeight);
        }

        mTempViews.clear();
    }


    /**
     * 判断视图是否需要被计算或者布局
     *
     * @param view
     * @return
     */
    private boolean shouldLayout(View view) {
        return view != null && view.getParent() == this && view.getVisibility() != GONE;
    }


    private int layoutChildRight(View child, int right, int[] collapsingMargins,
                                 int alignmentHeight) {
        final Toolbar.LayoutParams lp = (Toolbar.LayoutParams) child.getLayoutParams();
        final int r = lp.rightMargin - collapsingMargins[1];
        right -= Math.max(0, r);
        collapsingMargins[1] = Math.max(0, -r);
        final int top = getChildTop(child, alignmentHeight);
        final int childWidth = child.getMeasuredWidth();
        child.layout(right - childWidth, top, right, top + child.getMeasuredHeight());
        right -= childWidth + lp.leftMargin;
        return right;
    }


    public int getCurrentContentInsetLeft() {
        return ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL
                ? getCurrentContentInsetEnd()
                : getCurrentContentInsetStart();
    }


    private int getViewListMeasuredWidth(List<View> views, int[] collapsingMargins) {
        int collapseLeft = collapsingMargins[0];
        int collapseRight = collapsingMargins[1];
        int width = 0;
        final int count = views.size();
        for (int i = 0; i < count; i++) {
            final View v = views.get(i);
            final Toolbar.LayoutParams lp = (Toolbar.LayoutParams) v.getLayoutParams();
            final int l = lp.leftMargin - collapseLeft;
            final int r = lp.rightMargin - collapseRight;
            final int leftMargin = Math.max(0, l);
            final int rightMargin = Math.max(0, r);
            collapseLeft = Math.max(0, -l);
            collapseRight = Math.max(0, -r);
            width += leftMargin + v.getMeasuredWidth() + rightMargin;
        }
        return width;
    }


    /**
     * Returns the width + uncollapsed margins
     */
    private int measureChildCollapseMargins(View child,
                                            int parentWidthMeasureSpec, int widthUsed,
                                            int parentHeightMeasureSpec, int heightUsed, int[] collapsingMargins) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int leftDiff = lp.leftMargin - collapsingMargins[0];
        final int rightDiff = lp.rightMargin - collapsingMargins[1];
        final int leftMargin = Math.max(0, leftDiff);
        final int rightMargin = Math.max(0, rightDiff);
        final int hMargins = leftMargin + rightMargin;
        collapsingMargins[0] = Math.max(0, -leftDiff);
        collapsingMargins[1] = Math.max(0, -rightDiff);

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                getPaddingLeft() + getPaddingRight() + hMargins + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        return child.getMeasuredWidth() + hMargins;
    }

    private int getVerticalMargins(View v) {
        final MarginLayoutParams mlp = (MarginLayoutParams) v.getLayoutParams();
        return mlp.topMargin + mlp.bottomMargin;
    }

    private int getHorizontalMargins(View v) {
        final MarginLayoutParams mlp = (MarginLayoutParams) v.getLayoutParams();
        return MarginLayoutParamsCompat.getMarginStart(mlp) +
                MarginLayoutParamsCompat.getMarginEnd(mlp);
    }


    /**
     * Returns true if the Toolbar is collapsible and has no child views with a measured size > 0.
     */
    private boolean shouldCollapse() {
        return false;
//        if (!mCollapsible) return false;
//
//        final int childCount = getChildCount();
//        for (int i = 0; i < childCount; i++) {
//            final View child = getChildAt(i);
//            if (shouldLayout(child) && child.getMeasuredWidth() > 0 &&
//                    child.getMeasuredHeight() > 0) {
//                return false;
//            }
//        }
//        return true;
    }

    /**
     * 得到当前内容的结束
     *
     * @return
     */
    public int getCurrentContentInsetEnd() {
        boolean hasActions = false;
//        if (mMenuView != null) {
//            final MenuBuilder mb = mMenuView.peekMenu();
//            hasActions = mb != null && mb.hasVisibleItems();
//        }
//        return hasActions
//                ? Math.max(getContentInsetEnd(), Math.max(mContentInsetEndWithActions, 0))
//                : getContentInsetEnd();
        return 0;
    }


    /**
     * 得到当前控件的开始
     *
     * @return
     */
    public int getCurrentContentInsetStart() {
//        return getNavigationIcon() != null
//                ? Math.max(getContentInsetStart(), Math.max(mContentInsetStartWithNavigation, 0))
//                : getContentInsetStart();

        return getContentInsetStart();
    }

    public int getContentInsetStart() {
//        return mContentInsets != null ? mContentInsets.getStart() : 0;
        return 0;
    }


    /**
     * 设置标题文字颜色
     *
     * @param color The new text color in 0xAARRGGBB format
     */
    public void setTitleTextColor(@ColorInt int color) {
        mTitleTextColor = color;
        if (mTitleTextView != null) {
            mTitleTextView.setTextColor(color);
        }
    }


    /**
     * 在这个toolbar控件 设置标题
     * <p>
     * <p>A title should be used as the anchor for a section of content. It should
     * describe or name the content being viewed.</p>
     *
     * @param title 要设置的title
     */
    public void setTitle(CharSequence title) {
        if (!TextUtils.isEmpty(title)) {
            if (mTitleTextView == null) {
                final Context context = getContext();
                mTitleTextView = new AppCompatTextView(context);
                mTitleTextView.setSingleLine();
                mTitleTextView.setEllipsize(TextUtils.TruncateAt.END);
                if (mTitleTextAppearance != 0) {
                    mTitleTextView.setTextAppearance(context, mTitleTextAppearance);
                }
                if (mTitleTextColor != 0) {
                    mTitleTextView.setTextColor(mTitleTextColor);
                }
            }
            if (!isChildOrHidden(mTitleTextView)) {
                addSystemView(mTitleTextView, true);
                LayoutParams layoutParams = (LayoutParams) mTitleTextView.getLayoutParams();

                layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
                mTitleTextView.setLayoutParams(layoutParams);
            }
        } else if (mTitleTextView != null && isChildOrHidden(mTitleTextView)) {
            removeView(mTitleTextView);
            mHiddenViews.remove(mTitleTextView);
        }
        if (mTitleTextView != null) {
            mTitleTextView.setText(title);
        }
        mTitleText = title;
    }


    /**
     * 设置导航视图图标
     *
     * @param icon
     */
    public void setNavigationIcon(@Nullable Drawable icon) {
        if (icon != null) {
            ensureNavButtonView();
            if (!isChildOrHidden(mNavButtonView)) {
                addSystemView(mNavButtonView, true);
            }
        } else if (mNavButtonView != null && isChildOrHidden(mNavButtonView)) {
            removeView(mNavButtonView);
            mHiddenViews.remove(mNavButtonView);
        }
        if (mNavButtonView != null) {
            mNavButtonView.setImageDrawable(icon);
        }
    }

    /**
     * 设置导航内容描述
     *
     * @param resId
     */
    public void setNavigationContentDescription(@StringRes int resId) {
        setNavigationContentDescription(resId != 0 ? getContext().getText(resId) : null);
    }

    /**
     * 设置导航内容描述
     *
     * @param description
     */
    public void setNavigationContentDescription(@Nullable CharSequence description) {
        if (!TextUtils.isEmpty(description)) {
            ensureNavButtonView();
        }
        if (mNavButtonView != null) {
            mNavButtonView.setContentDescription(description);
        }
    }

    /**
     * 启动导航视图
     */
    private void ensureNavButtonView() {
        if (mNavButtonView == null) {
            mNavButtonView = new AppCompatImageButton(getContext(), null,
                    android.support.v7.appcompat.R.attr.toolbarNavigationButtonStyle);
            final SimpleToolbar.LayoutParams lp = generateDefaultLayoutParams();
            lp.gravity = GravityCompat.START | (mButtonGravity & Gravity.VERTICAL_GRAVITY_MASK);
            mNavButtonView.setLayoutParams(lp);
        }
    }


    /**
     * --------------------------------------------------分割线------------------------------------------
     */

    private void measureChildConstrained(View child, int parentWidthSpec, int widthUsed,
                                         int parentHeightSpec, int heightUsed, int heightConstraint) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        int childWidthSpec = getChildMeasureSpec(parentWidthSpec,
                getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        int childHeightSpec = getChildMeasureSpec(parentHeightSpec,
                getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        final int childHeightMode = MeasureSpec.getMode(childHeightSpec);
        if (childHeightMode != MeasureSpec.EXACTLY && heightConstraint >= 0) {
            final int size = childHeightMode != MeasureSpec.UNSPECIFIED ?
                    Math.min(MeasureSpec.getSize(childHeightSpec), heightConstraint) :
                    heightConstraint;
            childHeightSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
        }
        child.measure(childWidthSpec, childHeightSpec);
    }


    /**
     * 判断视图是否为子视图 或者 隐藏视图 如果是返回true
     *
     * @param child
     * @return
     */
    private boolean isChildOrHidden(View child) {
        return child.getParent() == this || mHiddenViews.contains(child);
    }

    /**
     * 添加视图到父视图
     *
     * @param v
     * @param allowHide
     */
    private void addSystemView(View v, boolean allowHide) {
        final ViewGroup.LayoutParams vlp = v.getLayoutParams();
        final LayoutParams lp;
        if (vlp == null) {
            lp = generateDefaultLayoutParams();
        } else if (!checkLayoutParams(vlp)) {
            lp = generateLayoutParams(vlp);
        } else {
            lp = (LayoutParams) vlp;
        }

        lp.mViewType = SimpleToolbar.LayoutParams.SYSTEM;

        if (allowHide && mExpandedActionView != null) {
            v.setLayoutParams(lp);
            mHiddenViews.add(v);
        } else {
            addView(v, lp);
        }
    }


    /**
     * 添加自定义视图集合 用 布局
     *
     * @param views
     * @param gravity
     */
    private void addCustomViewsWithGravity(List<View> views, int gravity) {
        final boolean isRtl = ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL;
        final int childCount = getChildCount();
        final int absGrav = GravityCompat.getAbsoluteGravity(gravity,
                ViewCompat.getLayoutDirection(this));

        views.clear();

        if (isRtl) {
            for (int i = childCount - 1; i >= 0; i--) {
                final View child = getChildAt(i);
                final SimpleToolbar.LayoutParams lp = (SimpleToolbar.LayoutParams) child.getLayoutParams();
                if (lp.mViewType == SimpleToolbar.LayoutParams.CUSTOM && shouldLayout(child) &&
                        getChildHorizontalGravity(lp.gravity) == absGrav) {
                    views.add(child);
                }
            }
        } else {
            for (int i = 0; i < childCount; i++) {
                final View child = getChildAt(i);
                final SimpleToolbar.LayoutParams lp = (SimpleToolbar.LayoutParams) child.getLayoutParams();
                if (lp.mViewType == SimpleToolbar.LayoutParams.CUSTOM && shouldLayout(child) &&
                        getChildHorizontalGravity(lp.gravity) == absGrav) {
                    views.add(child);
                }
            }
        }
    }


    private int getChildHorizontalGravity(int gravity) {
        final int ld = ViewCompat.getLayoutDirection(this);
        final int absGrav = GravityCompat.getAbsoluteGravity(gravity, ld);
        final int hGrav = absGrav & Gravity.HORIZONTAL_GRAVITY_MASK;
        switch (hGrav) {
            case Gravity.LEFT:
            case Gravity.RIGHT:
            case Gravity.CENTER_HORIZONTAL:
                return hGrav;
            default:
                return ld == ViewCompat.LAYOUT_DIRECTION_RTL ? Gravity.RIGHT : Gravity.LEFT;
        }
    }


    private int layoutChildLeft(View child, int left, int[] collapsingMargins,
                                int alignmentHeight) {
        final SimpleToolbar.LayoutParams lp = (SimpleToolbar.LayoutParams) child.getLayoutParams();
        final int l = lp.leftMargin - collapsingMargins[0];
        left += Math.max(0, l);
        collapsingMargins[0] = Math.max(0, -l);
        final int top = getChildTop(child, alignmentHeight);
        final int childWidth = child.getMeasuredWidth();
        child.layout(left, top, left + childWidth, top + child.getMeasuredHeight());
        left += childWidth + lp.rightMargin;
        return left;
    }

    private int getChildTop(View child, int alignmentHeight) {
        final SimpleToolbar.LayoutParams lp = (SimpleToolbar.LayoutParams) child.getLayoutParams();
        final int childHeight = child.getMeasuredHeight();
        final int alignmentOffset = alignmentHeight > 0 ? (childHeight - alignmentHeight) / 2 : 0;
        switch (getChildVerticalGravity(lp.gravity)) {
            case Gravity.TOP:
                return getPaddingTop() - alignmentOffset;

            case Gravity.BOTTOM:
                return getHeight() - getPaddingBottom() - childHeight
                        - lp.bottomMargin - alignmentOffset;

            default:
            case Gravity.CENTER_VERTICAL:
                final int paddingTop = getPaddingTop();
                final int paddingBottom = getPaddingBottom();
                final int height = getHeight();
                final int space = height - paddingTop - paddingBottom;
                int spaceAbove = (space - childHeight) / 2;
                if (spaceAbove < lp.topMargin) {
                    spaceAbove = lp.topMargin;
                } else {
                    final int spaceBelow = height - paddingBottom - childHeight -
                            spaceAbove - paddingTop;
                    if (spaceBelow < lp.bottomMargin) {
                        spaceAbove = Math.max(0, spaceAbove - (lp.bottomMargin - spaceBelow));
                    }
                }
                return paddingTop + spaceAbove;
        }
    }


    private int getChildVerticalGravity(int gravity) {
        final int vgrav = gravity & Gravity.VERTICAL_GRAVITY_MASK;
        switch (vgrav) {
            case Gravity.TOP:
            case Gravity.BOTTOM:
            case Gravity.CENTER_VERTICAL:
                return vgrav;
            default:
                return mGravity & Gravity.VERTICAL_GRAVITY_MASK;
        }
    }


    @Override
    protected SimpleToolbar.LayoutParams generateDefaultLayoutParams() {
        return new SimpleToolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);
    }

    @Override
    protected SimpleToolbar.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
        if (p instanceof SimpleToolbar.LayoutParams) {
            return new SimpleToolbar.LayoutParams((SimpleToolbar.LayoutParams) p);
        } else if (p instanceof ActionBar.LayoutParams) {
            return new SimpleToolbar.LayoutParams((ActionBar.LayoutParams) p);
        } else if (p instanceof MarginLayoutParams) {
            return new SimpleToolbar.LayoutParams((MarginLayoutParams) p);
        } else {
            return new SimpleToolbar.LayoutParams(p);
        }
    }


    /**
     * 自定义的layout
     */
    public static class LayoutParams extends ActionBar.LayoutParams {
        static final int CUSTOM = 0;
        static final int SYSTEM = 1;
        static final int EXPANDED = 2;

        int mViewType = CUSTOM;

        public LayoutParams(@NonNull Context c, AttributeSet attrs) {
            super(c, attrs);
        }

        public LayoutParams(int width, int height) {
            super(width, height);
            this.gravity = Gravity.CENTER_VERTICAL | GravityCompat.START;
        }

        public LayoutParams(int width, int height, int gravity) {
            super(width, height);
            this.gravity = gravity;
        }

        public LayoutParams(int gravity) {
            this(WRAP_CONTENT, MATCH_PARENT, gravity);
        }

        public LayoutParams(SimpleToolbar.LayoutParams source) {
            super(source);

            mViewType = source.mViewType;
        }

        public LayoutParams(ActionBar.LayoutParams source) {
            super(source);
        }

        public LayoutParams(MarginLayoutParams source) {
            super(source);
            // ActionBar.LayoutParams doesn't have a MarginLayoutParams constructor.
            // Fake it here and copy over the relevant data.
            copyMarginsFromCompat(source);
        }

        public LayoutParams(ViewGroup.LayoutParams source) {
            super(source);
        }

        void copyMarginsFromCompat(MarginLayoutParams source) {
            this.leftMargin = source.leftMargin;
            this.topMargin = source.topMargin;
            this.rightMargin = source.rightMargin;
            this.bottomMargin = source.bottomMargin;
        }
    }
}
